/*
 * File Name:               UIInterfaceEditor.cs
 *
 * Description:             普通类
 * Author:                  lisiyu
 * Create Date:             2016/08/02
 */

using UnityEditor;
using UnityEngine;

[CustomEditor(typeof(UIContext))]
public class UIContextEditor : Editor
{
    public override void OnInspectorGUI()
    {
        var context = target as UIContext;
        var components = context.pComponents;
        if (components == null)
            components = new UIContext.Data[0];

        GUILayout.Box("UI上下文信息", GUILayout.ExpandWidth(true));

        EditorGUILayout.BeginHorizontal();
        GUILayout.Box("删除", GUILayout.Width(30));
        GUILayout.Box("id", GUILayout.Width(30));
        GUILayout.Box("组件", GUILayout.Width(100));
        GUILayout.Box("组件功能描述", GUILayout.ExpandWidth(true));
        EditorGUILayout.EndHorizontal();

        for (int i = 0; i < components.Length; i++)
        {
            var child = components[i];

            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button("-", GUILayout.Width(30)))
            {
                context.pComponents = arrRemove(components, child);
                return;
            }

            GUILayout.Box(i + "", GUILayout.Width(30));
            child.pComponent = EditorGUILayout.ObjectField(child.pComponent, typeof(Transform), true, GUILayout.Width(100)) as Transform;
            child.pDescription = (EditorGUILayout.TextField(child.pDescription));
            EditorGUILayout.EndHorizontal();
        }

        if (GUILayout.Button("添加组件"))
        {
            context.pComponents = arrAdd(components, new UIContext.Data());
        }
    }

    /// <summary>
    /// 从数组中移除某个单项 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="arrary"></param>
    /// <param name="item">  </param>
    private T[] arrRemove<T>(T[] arrary, T item)
    {
        var ret = new T[arrary.Length - 1];
        for (int i = 0, j = 0; i < ret.Length; i++, j++)
        {
            var old = arrary[j];
            if (old.Equals(item))
                old = arrary[++j];
            ret[i] = old;
        }
        return ret;
    }

    /// <summary>
    /// 从数组中移除某个单项 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="arrary"></param>
    /// <param name="item">  </param>
    private T[] arrAdd<T>(T[] arrary, T item)
    {
        var ret = new T[arrary.Length + 1];
        arrary.CopyTo(ret, 0);
        ret[arrary.Length] = item;
        return ret;
    }
}